﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects.DataClasses;
using Entities;
using Entities.Modelo;
using System.Data.Objects;
using System.Reflection;

namespace DataAccessLayer
{
    public class EntityFramework_Dal<T> : ICadastro<T, Int32> where T : class, IEntityWithKey, IEntityID, new()
    {

        protected GICMC_dataBaseEntities1 dataContext = null;

        public EntityFramework_Dal()
        {

        }


        public virtual void InserirCadastro(T entity)
        {

            using (this.dataContext = new GICMC_dataBaseEntities1())
            {

                this.dataContext.AddObject(dataContext.GetEntitySet<T>().Name, entity);

                this.dataContext.SaveChanges();
            }

        }

        public virtual void AlterarCadastro(T entity)
        {
            using (this.dataContext = new GICMC_dataBaseEntities1())
            {
                object originalItem;
                Type type = typeof(T);

                EntityKey key = dataContext.CreateEntityKey(entity.EntityKey.EntitySetName, entity);

                if (dataContext.TryGetObjectByKey(key, out originalItem))
                {
                    dataContext.ApplyCurrentValues(key.EntitySetName, entity);
                }
                dataContext.SaveChanges();
            }

        }

        public virtual void ExcluirCadastro(T entity)
        {

            using (this.dataContext = new GICMC_dataBaseEntities1())
            {
                object originalItem;
                EntityKey key = dataContext.CreateEntityKey(entity.EntityKey.EntitySetName, entity);
                if (dataContext.TryGetObjectByKey(key, out originalItem))
                {
                    dataContext.DeleteObject(originalItem);
                }
                this.dataContext.SaveChanges();
            }

        }

        public virtual T RetornarCadastro(int chave)
        {

            using (this.dataContext = new GICMC_dataBaseEntities1())//Nova instancia para o objeto.
            {

                Type type = this.dataContext.GetType();
                PropertyInfo info = type.GetProperty(dataContext.GetEntitySet<T>().Name);
                Object value = info.GetValue(this.dataContext, null);

                ObjectQuery<T> query = null;

                if (value != null)
                {
                    query = (ObjectQuery<T>)value;
                }
                else
                {
                    throw new InvalidOperationException("Dal: Objeto QueryObject não pode ser nulo");
                }

                return query.FirstOrDefault();

            }

        }
    }
}
